package com.socket.server.custom;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.RandomUtil;
import com.socket.core.constant.Constants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Shiro基于Redis储存Session
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RedisSessionDao extends AbstractSessionDAO {
    private static final String PREFIX = "SESSION:";
    private RedisTemplate<String, Serializable> template;

    @Override
    protected Serializable doCreate(Session session) {
        // 生成SessionID
        String id = RandomUtil.randomString(32).toUpperCase();
        assignSessionId(session, id);
        long time = Constants.SESSION_VALID_TIME;
        template.opsForValue().set(PREFIX + id, (Serializable) session, time, TimeUnit.SECONDS);
        return id;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return (SimpleSession) template.opsForValue().get(PREFIX + sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session != null && session.getId() != null) {
            String key = PREFIX + session.getId();
            Long expire = template.getExpire(key, TimeUnit.SECONDS);
            if (expire != null) {
                template.opsForValue().setIfPresent(key, (Serializable) session, expire, TimeUnit.SECONDS);
            }
        }
    }

    @Override
    public void delete(Session session) {
        template.delete(PREFIX + session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<String> keys = template.keys(PREFIX + "*");
        if (keys != null) {
            return keys.stream()
                    .map(e -> e.replace(PREFIX, ""))
                    .map(this::doReadSession)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
        return ListUtil.empty();
    }

    @Autowired
    public void afterPropertiesSet(LettuceConnectionFactory factory) {
        this.template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
    }
}
